from ..gtkBaseUI import BaseContainer
from ..devicetree import DeviceTree
from ..bases import widgets
from .. import editors

class CueStackView(BaseContainer):
    topwidget_name = 'Universes'
    topwidget_cls = widgets.HPane
    def __init__(self, **kwargs):
        self.topwidget = widgets.VBox()
        super(CueStackView, self).__init__(**kwargs)
        self.MainController = kwargs.get('MainController')
        
        self.stack_editor = None
        
        frame = self.make_child_widget(widgets.Frame, 'frame1', label='Stacks')
        col_names = ['id', 'name']
        obj_names = ['Stack']
        self.stack_list = DeviceTree(col_names=col_names, obj_names=obj_names, child_name_attr='none', 
                                     show_dicts=False, base_dict=self.MainController.CueStacks, used_columns=[1])
        self.stack_list.widget.connect('selection_changed', self.on_stack_list_selection_changed)
        frame.pack_start(self.stack_list.widget.topwidget, expand=True)
        
        hbox = widgets.HBox()
        d = {'btnNewStack':'New Cue Stack', 'btnDelStack':'Delete', 'btnRefresh':'Refresh'}
        for k, v in d.iteritems():
            btn = self.make_child_widget(widgets.Button, k, label=v)
            btn.connect('clicked', self.on_stack_list_btns_clicked, k)
            hbox.pack_start(btn)
        frame.pack_start(hbox)
        
        self.topcontainer.pack_start(frame)
        
        self.MainController.connect('child_added', self.on_mc_child_added)
        
        self.topwidget.show_all()
    
    def set_current_stack(self, obj):
        if self.stack_editor is not None:
            self.stack_editor.unlink()
            self.topcontainer.remove(self.stack_editor.topwidget)
        self.stack_editor = editors.CueStackEditor(MainController=self.MainController, stack=obj)
        self.topcontainer.pack_start(self.stack_editor.topwidget, expand=True)
    
    def on_stack_list_selection_changed(self, **kwargs):
        obj = kwargs.get('obj')
        state = kwargs.get('state')
        if state and hasattr(obj, 'id'):
            self.set_current_stack(obj)
        
    def on_stack_list_btns_clicked(self, btn, key):
        if key == 'btnNewStack':
            stack = self.MainController.add_CueStack(name='New Stack')
            self.stack_list.tree.set_selection(stack.id)
        elif key == 'btnDelStack':
            pass
        elif key == 'btnRefresh':
            self.stack_list.tree.refresh_all()
                
    def on_mc_child_added(self, **kwargs):
        self.stack_list.tree.refresh_all()
